import datetime
import smtplib
from email.mime.text import MIMEText  # 邮件正文
from email.mime.base import MIMEBase  # 附件的对象
from email.mime.multipart import MIMEMultipart  # 代表邮件本身
from email import encoders


class SendEmail:
    def __init__(self, recevices):
        """
        :param recevices: 收件人
        """
        self.mail_host = 'smtp.qq.com'  # qq服务器
        self.sender = 'xuesongtao512@qq.com'
        self.password = 'vtagigvquhxcbbfa'
        self.receive = ';'.join(recevices)  # 只有是list就必须要这个
        # alternative"的邮件包括纯文本正文（text/plain）和超文本正文（text/html）
        # related"的邮件正文中包括图片，声音等内嵌资源
        # mixed"的邮件包含附件。向上兼容，如果一个邮件有纯文本正文，超文本正文，内嵌资源，附件，则选择mixed类型
        self.msg = MIMEMultipart('mixed')

    def send_html_course(self, html_path, subject):
        """
        :param html_path: html路径
        :param subject: 邮件主题
        """
        # 构造邮件头部
        self.msg['from'] = self.sender
        self.msg['to'] = self.receive
        self.msg['subject'] = '%s' % subject
        with open(html_path, 'rb+') as f:
            mail_body = f.read()
            content = mail_body
        # 构造正文
        msg_html = MIMEText(content, _subtype='html', _charset='utf-8')  # 需要html
        self.msg.attach(msg_html)  # 加载到MIMEMultipart

    def send_message(self, subject, content):
        """
        :param subject: 邮件主题
        :param content: 邮件内容
        """
        msg_message = MIMEText(content, _subtype='plain', _charset='utf-8')
        self.msg['from'] = self.sender
        self.msg['to'] = self.receive
        self.msg['subject'] = '%s' % subject
        self.msg.attach(msg_message)

    def send_accessory(self, subject, file_path, file_name, file_format):
        """
        添加附件
        :param subject: 邮件主题
        :param file_path: 附件路径
        :param file_name: 附件名字
        :param file_format: 附件格式
        """
        self.msg['from'] = self.sender
        self.msg['to'] = self.receive
        self.msg['subject'] = '%s' % subject
        with open(file_path, 'rb+') as f:
            test_html = f.read()
            text_html = MIMEText(test_html, _subtype='html', _charset='utf-8')
            # 指定当前文件格式类型
            text_html["Content-Type"] = 'application/octet-stream'
            text_html["Content-Disposition"] = 'attachment; filename="%s.%s"' % (
                file_name.encode('utf-8').decode('utf-8'), file_format)
            self.msg.attach(text_html)

    def send_image(self, subject, text, image_path):
        """
        发送正文带有图片，文字
        :param subject: 邮件主题
        :param text: 邮件正文
        :param image_path: 图片路径
        """
        self.msg['from'] = self.sender
        self.msg['to'] = self.receive
        self.msg['subject'] = '%s' % subject
        # 已添加正文的形式发送图片
        self.msg.attach(MIMEText('<html><body><h1>%s</h1>' % text +
                                 '<p><img src="cid:0"></p>' +
                                 '</body></html>', 'html', 'utf-8'))  # 1.如果有多个图片为cid:x
        with open(image_path, 'rb') as f:
            mm = MIMEBase(_maintype='image', _subtype='jpg', filename='b.jbp')  # 选择类型
            # 加上必要的头部信息
            mm.add_header(_name='Content-ID', _value='<0>')
            mm.add_header(_name='X-Attachment-Id', _value='0')
            mm.set_payload(f.read())
            encoders.encode_base64(mm)  # 用Base64编码
            self.msg.attach(mm)

    def __del__(self):
        try:  # 发送邮件
            server = smtplib.SMTP()
            # server.set_debuglevel(1)  # 加上这句就可以打印出所有的log，更方便我们定位问题
            server.connect(self.mail_host)
            server.login(self.sender, self.password)
            server.sendmail(self.sender, self.receive, self.msg.as_string())
            server.close()
            print('%s----发送邮件成功' % datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))  # 当前时间
        except Exception as e:
            print(e)


if __name__ == '__main__':
    # SendEmail(['xuesongtao512@qq.com']).send_html_course(r'E:\python_all\python_test\study_All\Uint_test\HTMLTestRunner.html','第一次测试')
    # recevice = ['xuesongtao512@qq.com']  # 如果是一个邮箱的话就只有'xuesongtao512@qq.com'，如果多个就要用到list
    # SendEmail(['xuesongtao512@qq.com']).send_accessory('test',
    #                                                    r'C:\Users\lenovo\Desktop\thinkpad.jpg',
    #                                                    'jpg')
    SendEmail(['xuesongtao512@qq.com']).send_image('珊姐姐', '丑娃子', r'C:\Users\lenovo\Desktop\thinkpad.jpg')
    # SendEmail(['838190924@qq.com']).send_message('填写模拟数据',
    #                                              '成功填写------%s' % datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    # SendEmail(['838190924@qq.com']).send_image('test','nihao',r'C:\Users\Administrator\Desktop\img13.bmp')
